import router from './router'
import store from './store'

import { ElMessageBox, ElMessage } from "element-plus";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {
  getToken
} from '@/utils/auth'
// import getPageTitle from '@/utils/get-page-title'

NProgress.configure({
  showSpinner: false
})

//! 白名单列表
const whiteList = ['/login', '/formPreview']

router.beforeEach(async (to, from, next) => {
  //console.log("登录后进入的界面", to)
  // start progress bar
  NProgress.start()

  // set page title
  // document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  //! 获取cookie的token值判断用户是否已登录
  const hasToken = getToken()
  // next()
  //console.log('to.path', to.path, hasToken)
  if (to.path == '/mechanical') {
    store.commit("settings/SITE_CHANGEOVER", false);
  }
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      const loginResInfo = store.state.loginResInfo
      if (loginResInfo) {
        next()
      } else {
        try {
          //! 验证用户的登录状态
          // await store.dispatch('user/getInfo')
          getToken()
          next()
        } catch (error) {
          // 清除token返回到登录界面
          await store.dispatch('user/resetToken')
          // this.$router.push(`/login?redirect=${this.$route.fullPath}`);
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    //! 没有token值时遍历白名单存在的值即可直接访问 
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {

      //! 没有权限的界面返回到登录界面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
